import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import router from './router'
import store from './store'
import axios from 'axios'

// 配置axios默认值 - 使用相对路径，让Vite代理处理
axios.defaults.baseURL = ''
axios.defaults.timeout = 10000
axios.defaults.withCredentials = true

console.log('Axios baseURL configured as:', axios.defaults.baseURL)

// 请求拦截器 - 自动添加Authorization头
axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token') || sessionStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    console.log('Making request to:', config.url, 'with baseURL:', config.baseURL)
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理认证错误
axios.interceptors.response.use(
  response => {
    return response
  },
  error => {
    console.error('Request failed:', error.config?.url, error.response?.status, error.response?.data)
    if (error.response?.status === 401) {
      // Token过期或无效，清除本地存储并跳转到登录页
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('userInfo')
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

const app = createApp(App);
app.use(ElementPlus)
app.use(store)
app.use(router)
app.mount('#app')

